<?php
namespace Home\Controller;
use Common\Model\OrderModel;
use Think\Controller;
use Think\Exception;
use Think\Model;

/**
 * 售后退款
 * @package Home\Controller
 */
class MemberRefundGoodsController extends BaseController {
    public $obj;
    public $member_id;
    public function __construct(){
        parent::__construct();

        $this->obj = M('b2c_members');
        $this->member_id = $this->member_data['member_id'];
        if(!$this->member_id){
            $this->redirect('Login/index');
        }
    }

    /**
     * 退款首页
     */
    public function index(){
        $order_id = I('order_id', '', htmlspecialchars());
        $sell = I('sell', '', htmlspecialchars()); // 售前退款

        if ($sell != 'refund_ago_money_status') {
            $this->error('错误退款');
        }

        $order = new OrderModel();
        $orderMsg = $order->getOrderMsg($order_id, $this->member_id); // 查询订单信息
        if ($orderMsg['pay_status'] != 1) { // 判断订单是否已经购买
            $this->error('改订单没有支付');
        }
        $goodsMsg = M('b2c_order_items')->where(['order_id' => $orderMsg['order_id']])->select();

        $refund_goods_num = $this->get_refund_goods_num($order_id);

        // 计算退款商品数量保存refund_goods_num
        if ($refund_goods_num) {
            for ($i=0; $i<count($goodsMsg); $i++){
                for($j=0; $j<count($refund_goods_num[0]); $j++) {
                    if ($goodsMsg[$i]['item_id'] == $refund_goods_num[0][$j]['item_id']) {
                        $goodsMsg[$i]['refund_goods_num'] = $refund_goods_num[0][$j]['b_num'];
                    }
                }
            }
        }

        $b2c_refund_money = M('b2c_refund_money');
        $refund = $b2c_refund_money->where(['order_id' => $order_id, 'type' => '2', 'status' => ['NEQ', '6']])->order('id desc')->find(); // 退款

        $this->assign([
            'sell' => $sell
        ]);

        // 获取电话
        $order_id = I('order_id');
        $order = new OrderModel();
        $orderMsg = $order->getOrderMsg($order_id, $this->member_id); // 查询订单信息
        $store = M('webpos_local_store')->field('mobile')->where(['local_id' => $orderMsg['local_id']])->find();
        $this->assign('mobile',$store['mobile']);

        if ($refund['status'] == '1' || $refund['status'] == '0' || $refund['status'] == '2') {

            $this->assign([
                'refund' => $refund
            ]);
            $this->display('indexSecond');

        }elseif ($refund['status'] == '5'){
            $this->assign([
                'refund' => $refund,
            ]);
            $this->display('indexThird');

        }else{
            $this->assign([
                'goodsMsg' => $goodsMsg,
                'orderMsg' => $orderMsg
            ]);
            $this->display();
        }
    }

    /**
     * 获取商品退款数量
     */
    public function get_refund_goods_num($order_id){
        $b2c_refund_money = M('b2c_refund_money')->where(['order_id' => $order_id, 'status' => '5'])->select();
        if ($b2c_refund_money) {
            $refund_money_goods = [];
            foreach ($b2c_refund_money as $v) {
                $refund_money_goods[] = M('b2c_refund_money_goods')
                    ->field('id,num,order_id,item_id,sum(num) AS b_num')
                    ->where(['order_id' => $order_id,'refund_money_id' => $v['id']])
                    ->group('item_id')
                    ->select();
            }
            if (!empty($refund_money_goods)) {
                return $refund_money_goods;
            }
        }
        return false;
    }

    /**
     *退款第二部
     */
    public function indexSecond(){
        $this->display();
    }

    public function indexThird(){
        $this->display();
    }

    /**
     * ajax首页退款
     */
    public function ajax_refund(){
        $order_id = I('post.order_id', '', intval()); // 订单id
        $price = I('post.price', '', htmlspecialchars());
        $message = I('post.message', '', htmlspecialchars());
        $comment = I('post.comment', '', htmlspecialchars());
        $item_id = I('post.item_id', '', htmlspecialchars());
        $cost_freight = I('post.cost_freight', '', htmlspecialchars()); // 运费
        $sell = I('sell', '', htmlspecialchars()); // 售前退款

        if ($sell != 'refund_ago_money_status') {
            $this->error('退款信息错误');
        }

        $model = new Model();
        $flag = 1;
        try{
            $model->startTrans();

            $b2c_refund_money = M('b2c_refund_money'); // 退款信息表

            $order = new OrderModel();
            $orderMsg = $order->getOrderMsg($order_id, $this->member_id); // 查询订单信息

            if (empty($orderMsg)) { // 如果订单没有
                throw new Exception("error1");
            }

            if ($orderMsg['pay_status'] != '1') { // 不等于1没有支付
                throw new Exception("error2");
            }

            if ($orderMsg['status'] != 'active') { // 订单状态不是活动中就不能退货
                throw new Exception("error3");
            }
/*            if ($orderMsg['refund_status'] != '0') { // 退款状态
                throw new Exception("error4");
            }*/

            if ($orderMsg['refund_ago_goods_status'] > '0' || $orderMsg['refund_ago_money_status'] != '0') { // 售后只能申请一次退款或者退货
                throw new Exception("error5");
            }

            $update_order = $order->where(['order_id' => $order_id])->save(['refund_ago_money_status' => '1', 'order_msg' => '售后申请退款']); // 修改订单状态

            if ($update_order === false) {
                throw new Exception("error9");
            }

            $time = time();
            $data = [
                'json_msg' => json_encode(['b' => ['time' => $time]]), // a=0取消退款,b=1售前退款状态,c=2.....
                'order_id' => $order_id,
                'member_id' => $this->member_id,
                'price' => $price,
                'status' => '1', // 申请退款中
                'message' => $message,
                'comment' => $comment,
                'type' => '2', // 2售后退款
                'start_time' => $time,
                'cost_freight' => $cost_freight,
                'local_id' => $orderMsg['local_id'],
            ];

            $refund_money_id = $b2c_refund_money->add($data); // 增加退款数据

            if ($refund_money_id === false) {
                throw new Exception("error10");
            }

            // 退款订单日志记录
            $order_log = M('b2c_order_log')->add([
                'rel_id' => $order_id,
                'op_id' => $this->member_id,
                'op_name' => $this->member_data['mobile'],
                'alttime' => $time,
                'behavior' => 'member_refund',
                'result' => 'SUCCESS',
                'log_text' => '用户申请退款',
            ]);

            if ($order_log === false) {
                throw new Exception("error100");
            }

            $b2c_refund_money_goods = M('b2c_refund_money_goods');

            $item_array = explode(',', $item_id);// $item_id格式 = 【123#2,234#3】格式
            foreach ($item_array as $v) {

                $goods_array = explode('#', $v);
                $b2c_refund_money_goods_data = [
                    'refund_money_id' => $refund_money_id,
                    'order_id' => $order_id,
                    'item_id' => $goods_array[0],
                    'num' => $goods_array[1],
                ];
                $money_goods_result = $b2c_refund_money_goods->add($b2c_refund_money_goods_data); // 退款附表
                if ($money_goods_result === false) {
                    throw new Exception("error11");
                }
            }

            $model->commit();
        }catch (Exception $e){
            $model->rollback();
            $error = $e->getMessage();
            $flag = 0;
        }
        echo json_encode(['flag' => $flag, 'message' => $error]);
    }

    /**
     * 重新申请
     */
    public function ajaxReplay(){
        $order_id = I('order_id', '', intval());
        $id = I('id', '', intval());
        $sell = I('sell', '', htmlspecialchars()); // 售前退款

        if ($sell != 'refund_ago_money_status') {
            $this->error('重新退款错误');
        }

        $b2c_refund_money = M('b2c_refund_money');
        $refund = $b2c_refund_money->where(['order_id' => $order_id, 'type' => '2', 'id' => $id, 'member_id' => $this->member_id])->order('id desc')->find(); // 退款
        $flag = 1;
        $time = time();
        $model = new Model();
        try{
            $model->startTrans();
            $order = new OrderModel();

            $update_order = $order->where(['order_id' => $order_id])->save(['refund_ago_money_status' => '0', 'order_msg' => '售前重新申请退款']); // 修改订单退货状态

            if ($update_order === false) {
                throw new Exception("error1");
            }
            if (!empty($refund)) {
                $refund['json_msg'] = json_decode($refund['json_msg'], true);
                $refund['json_msg']['g'] = ['time' => $time];
                $json_msg = json_encode($refund['json_msg']);
                $update = $b2c_refund_money->where(['id' => $id])->save(['status' => '6', 'json_msg'=> $json_msg]); // 改为重新申请
                if ($update === false) {
                    throw new Exception("error2");
                }
            }
            $model->commit();
        }catch (Exception $e){
            $model->rollback();
            $flag = 0;
        }
        echo $flag;
    }

    /**
     * 取消订单退款
     */
    public function ajax_cancel_order(){
        $order_id = I('order_id', '', intval());
        $id = I('id', '', intval());
        $sell = I('sell', '', htmlspecialchars());

        $b2c_refund_money = M('b2c_refund_money');
        $refund = $b2c_refund_money->where(['order_id' => $order_id, 'type' => '2', 'id' => $id, 'member_id' => $this->member_id])->order('id desc')->find(); // 退款
        $flag = 1;
        $time = time();
        $model = new Model();
        try{
            $model->startTrans();

            if ($sell != 'refund_ago_money_status') {
                throw new Exception("error0");
            }
            $order = new OrderModel();

            $update_order = $order->where(['order_id' => $order_id])->save(['refund_ago_money_status' => '0', 'order_msg' => '售后取消申请退款']); // 修改订单退货状态

            if ($update_order === false) {
                throw new Exception("error1");
            }
            if (!empty($refund)) {
                $refund['json_msg'] = json_decode($refund['json_msg'], true);
                $refund['json_msg']['h'] = ['time' => $time];
                $json_msg = json_encode($refund['json_msg']);

                $update = $b2c_refund_money->where(['id' => $id])->save(['status' => '7', 'end_time' => time(),'json_msg' => $json_msg]); // 改为重新申请
                if ($update === false) {
                    throw new Exception("error2");
                }
            }
            $model->commit();
        }catch (Exception $e){
            $model->rollback();
            $flag = 0;
        }
        echo $flag;
    }

}